/*
 * Copyright (c) 2021.版权所有高金磊
 */

package 领扣算法.AA中等题.构成交替字符串需要的最小交换次数;

public class Main {
    public int minSwaps(String s) {
        int count=0;
        int c_middle=0,min_0=0,min_1=0;
        int sum_1=0;
        for (char c : s.toCharArray()) {
            c_middle=c-'0';
            sum_1+=c_middle;
            //the first letter is '0'
            if ((c_middle+count)%2==0){
                min_1++;
            }
            else {
                min_0++;
            }
            count++;
        }
        //分析可行性
        if (Math.abs(count-sum_1*2)>=2){
            return -1;
        }
        if (min_0<min_1){//优先使用小的
            //假设第一个为0
            if (count-sum_1*2>=0){
                return min_0/2;
            }
        }
        if (s.length()-sum_1*2<=0){
            return min_1/2;
        }
        if (count-sum_1*2>=0){
            return min_0/2;
        }

        return -1;
    }

}
